package cn.chaos.bio.exercise;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JHttpServerBio {


    private static final Logger logger = Logger.getLogger(JHttpServerBio.class.getCanonicalName());

    private static final int NUM_THREADS = 50;
    private static final String INDEX_FILE = "index.html";

    private final File rootDirectory;
    private final int port;

    public JHttpServerBio(File rootDirectory, int port) throws IOException {

        if (!rootDirectory.isDirectory()) {
            throw new IOException(rootDirectory +
                " does not exists as a directory");

        }

        this.rootDirectory = rootDirectory;
        this.port = port;
    }

    public void start() throws IOException {

        ExecutorService pool = Executors.newFixedThreadPool(NUM_THREADS);
        boolean running = true;

        try (ServerSocket server = new ServerSocket(port)) {
            logger.info("Accepting connection on port " + server.getLocalPort());
            logger.info("Document Root: " + rootDirectory);

            while (running && server != null) {
                try {
                    Socket request = server.accept();
                    Runnable r = new RequestProcessor(rootDirectory, INDEX_FILE, request);
                    pool.submit(r);
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Error accepting connection", e);
                }
            }
        }
    }

    public static void main(String[] args) {
        File docroot = new File("/Users/chengchao/temp/mydocroot");

        int port = 11111;

        try {
            JHttpServerBio webServer = new JHttpServerBio(docroot, port);
            webServer.start();

        } catch (IOException e) {
            logger.log(Level.SEVERE, "Server could not start", e);
        }
    }
}
